package cn.domypay.mail.base;

import java.security.Security;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.URLName;

import cn.domypay.mail.bean.Mailbox;
import cn.domypay.mail.conf.DomypayMail;

import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3Store;

public class Pop3Biz {
	
	private final static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	
	public Pop3Biz()
	{}
	/**
	 * 处理普通的POP3协议
	 * @param mailbox
	 * @return
	 */
	public Properties getPop3Prop(Mailbox mailbox)
	{
		Properties properties = new Properties();
		properties.put("mail.pop3.host", mailbox.getPop3Host());
		if("".equals(mailbox.getPop3Port()) || null == mailbox.getPop3Port())
		{
			mailbox.setPop3Port(DomypayMail.DEFAULT_POP3_PORT);
		}
		properties.put("mail.pop3.port", Integer.parseInt(mailbox.getPop3Port()));
		properties.put("mail.pop3.connectiontimeout", DomypayMail.DEFAULT_CONNECTION_TIMEOUT);
		
		return properties;
	}
	
	/**
	 * 处理基于ssl连接方式的POP3协议
	 * @param mailbox
	 * @return
	 */
	public Properties getPop3_SslProp(Mailbox mailbox)
	{
		Properties properties = new Properties();
		properties.put("mail.pop3.host", mailbox.getPop3Host());
		properties.put("mail.pop3.socketFactory.class",SSL_FACTORY);
		properties.put("mail.pop3.socketFactory.fallback", false);
		
		if("".equals(mailbox.getPop3Port()) ||null == mailbox.getPop3Port())
		{
			mailbox.setPop3Port(DomypayMail.DEFAULT_POP3_SSL_PORT);
		}
		properties.put("mail.pop3.port", Integer.parseInt(mailbox.getPop3Port()));
		properties.put("mail.pop3.socketFactory.port", Integer.parseInt(mailbox.getPop3Port()));

		properties.put("mail.pop3.connectiontimeout", DomypayMail.DEFAULT_CONNECTION_TIMEOUT);
		
		return properties;
	}
	
	public URLName getPop3URLName(Mailbox mailbox)
	{
		if("".equals(mailbox.getPop3Port()) || null == mailbox.getPop3Port())
		{
			if(DomypayMail.NEED_SSL.equals(mailbox.getPop3Ssl()))
			{
				mailbox.setPop3Port(DomypayMail.DEFAULT_POP3_SSL_PORT);
			}else{
				mailbox.setPop3Port(DomypayMail.DEFAULT_POP3_PORT);
			}
		}
		URLName name=new URLName("pop3",mailbox.getPop3Host(),Integer.parseInt(mailbox.getPop3Port()),null,mailbox.getUsername(),mailbox.getPassword());
		return name;
	}
	
	public void checkPop3(Session session,Mailbox mailbox) throws MessagingException
	{
		POP3Store store;
			
		if(DomypayMail.NEED_SSL.equals(mailbox.getPop3Ssl()))
		{
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			
		}
		store = new POP3Store(session,getPop3URLName(mailbox));
		store.connect();
		store.close();
	}
	
	public POP3Folder openPop3Connection(POP3Store store,POP3Folder folder,Mailbox mailbox,String READ_OR_WRITER,String MAIL_BOX) throws MessagingException{
		Properties prop = new Properties();
		
		if(DomypayMail.NEED_SSL.equals(mailbox.getPop3Ssl()))
		{
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			prop=getPop3_SslProp(mailbox);
		}else{
			prop=getPop3Prop(mailbox);
		}
		SwanetAuthenticate pAuth = new SwanetAuthenticate(mailbox
				.getUsername(), mailbox.getPassword());	
		Session session = Session.getInstance(prop,pAuth);
		store = new POP3Store(session,getPop3URLName(mailbox));
			
		store.connect();
		folder = (POP3Folder)store.getFolder(MAIL_BOX);
		if(READ_OR_WRITER.equals(DomypayMail.READ_ONLY))
		{
			folder.open(Folder.READ_ONLY);
		}else{
			folder.open(Folder.READ_WRITE);
		}
			
		return folder;
	}
	public void closePop3Connection(POP3Store store,POP3Folder folder) throws MessagingException{	
		
		if(folder.isOpen()){
			folder.close(true);
		}
		if(store.isConnected())
		{
			store.close();
		}
	}
//	public EmailMessage[] pop3Receive(POP3Folder folder,FetchProfile profile,CMailbox cmailbox,String path,int start,int end)
//	{
//		try {
//			List<EmailMessage> v = new ArrayList<EmailMessage>();
//			
//			Message[] messages = folder.getMessages();
//	
//			folder.fetch(messages, profile);
//			
//			EmailMessage msg = null;
//			
//			EmailMap map = EmailMap.getInstance();
//			
//			if (messages != null) {
//				List emailList = (List) map.get(cmailbox.getMailbox());
//				if (emailList == null)
//					emailList = new Vector();
//				for (int i = 0; i < messages.length; i++) {
//					
//					String messageID = folder.getUID(messages[i]);
//					
//					if (emailList.contains(messageID)) {
//						
//						continue;
//						
//					} else {
//						emailList.add(messageID);
//						map.put(cmailbox.getMailbox(), emailList);
//					}
//					String filename = EmailHelper.saveMessage(path, messages[i],
//							cmailbox.getCompanyID());
//					try {
//						msg = EmailHelper.parse(messages[i]);
//						msg.setHolder(cmailbox.getMailbox());
//						msg.setCompanyMailbox(cmailbox.getMailbox());
//						msg.setPath(filename);
//						msg.setCompanyID(cmailbox.getCompanyID());
//						msg.setMessageID(messageID);
//						v.add(msg);
//					} catch (Exception e) {
//						e.printStackTrace();
//						logger.logInfo("messages object info " + messages[i]);
//						logger.logError("Receive mail error:", e);
//						new DealException(cmailbox).sendNotification(messages[i], filename, e);
//					}
//					//����������ϵ��ʼ��Ƿ���Ҫɾ��
//					if (MailConstants.email_is_del.equals(cmailbox.getIsDelete())){
//						
//						messages[i].setFlag(javax.mail.Flags.Flag.DELETED, true);
//					}
//				}
//			}
//			
//			return (EmailMessage[]) v.toArray(new EmailMessage[0]);
//	} catch (MessagingException e) {
//		// TODO �Զ���� catch ��
//		e.printStackTrace();
//	}
//		return null;
//	}
}
